<template>
	<view class="layout-container">
		<view class="nav" style="margin-top: 20rpx;">
			<text>{{dataConfig.titleConfig.val}}</text>
			<view class="btn" @click="goMore(dataConfig.linkConfig.val)">
				更多<tui-icon name="arrowright" :size="15"></tui-icon>
			</view>
		</view>
		<view class="grid">
			<view v-for="(item, index) in dataConfig.newData" :key="index" :id="'media-' + index"
				@click="goDetail(item.url)" :class="['media-item', { 'full-width': index <topLength }]">
				<!-- 默认显示图片 -->
				<image v-if="!item.isPlaying" :src="item.img" class="media" mode="aspectFill"></image>
				<!-- 进入中间区域后播放视频 -->
				<view v-else :id="'video-' + index" :ref="'videoRef-' + index"
					style="width: 100%; height: 100%; border-radius: 20rpx;"></view>
				<view class="title">
					{{item.name}}
				</view>
			</view>
		</view>
		<MyUseOut :showModal="isUseOut" @close="isUseOut=false" />
	</view>
</template>

<script>
	// #ifdef H5
	import Hls from "hls.js";
	import Dplayer from "dplayer";
	// #endif
	export default {
		name: "MyTwoLayout",
		props: {
			dataConfig: {
				type: Object,
				default: () => {}
			},
			id: {
				type: Number,
				required: true
			}

		},
		watch: {
			dataConfig: {
				handler(newVal) {
					if (!newVal.menuBigConfig || !newVal.menuSmallConfig) return;
					this.topLength = newVal.menuBigConfig.length;
				},
				deep: true,
				immediate: true
			},
			videoStatus: {
				handler(newStatus) {
					this.dataConfig.forEach((item, index) => {
						const id = `media-${this.id}-${index}`;
						if (newStatus[id] && !item.isPlaying) {
							this.initVideoPlayer(`video-${this.id}-${index}`, item);
							this.$set(item, 'isPlaying', true);
						} else if (!newStatus[id] && item.isPlaying) {
							this.destroyPlayer(`video-${this.id}-${index}`);
							this.$set(item, 'isPlaying', false);
						}
					});
				},
				deep: true
			}
		},
		data() {
			return {
				hlsInstances: [],
				isUseOut: false,
				topLength: 0,
				videoPlayers: {},
			};
		},
		computed: {
			videoStatus() {
				return this.$parent.videoStatus;
			}
		},
		onLoad() {
			// 如果是从本页面的MyUseOut弹框进入三种增加次数的页面去了，并且成功后，再跳转到本页面要默认关闭弹窗
			uni.$on('closeModal', data => {
				this.isUseOut = data
			})
		},
		methods: {

			goDetail(url) {
				if (!uni.getStorageSync('infinite') ) {
					this.isUseOut = true
					return
				}
				// 必须调用ADDuser接口才会有viewsNum和useViewsNum值
				uni.navigateTo({
					url
				})
			},
			goMore(url) {
				uni.navigateTo({
					url
				})
			},
			isVideoPlaying(index) {
				const id = `media-${this.id}-${index}`;
				return this.videoStatus[id];
			},
			initVideoPlayer(idSelector, item) {
				const container = document.getElementById(idSelector);
				if (container) {
					const clips = [
						[60, 70], // 第一个片段：1分钟 - 1分10秒
						[100, 110],
						[160, 170],
						[200, 210],
						[220, 260]
					];

					let currentClipIndex = 0; // 记录当前播放片段索引
					let dp = new Dplayer({
						container: container,
						autoplay: true, // 自动播放
						muted: true, // 静音播放，防止浏览器阻止自动播放
						theme: "#000",
						loop: false, // DPlayer 自己循环，我们自己控制片段循环
						lang: "zh-cn",
						airplay: true,
						screenshot: false,
						hotkey: false,
						preload: "auto", // 预加载
						volume: 0,
						mutex: false, //允许多个播放器同时播放
						video: {
							url: item.video,
							pic: item.img,
							type: "customHls",

							customType: {
								customHls: function(video) {
									if (Hls.isSupported()) {
										const hls = new Hls();
										hls.loadSource(video.src);
										hls.attachMedia(video);
									} else if (video.canPlayType("application/vnd.apple.mpegurl")) {
										video.src = item.video;
									}
								},
							},
							playsInline: true, //允许在内嵌模式下播放
						},
					});
					dp.video.setAttribute("muted", "true");
					dp.video.setAttribute("playsinline", "true");

					dp.on('loadedmetadata', () => {
						dp.video.currentTime = clips[currentClipIndex][0]; // 跳到第一个片段
						dp.play();
					});

					dp.on('timeupdate', () => {
						const currentTime = dp.video.currentTime;
						const [start, end] = clips[currentClipIndex];

						if (currentTime >= end) {
							// 跳转到下一个片段
							currentClipIndex = (currentClipIndex + 1) % clips.length;
							dp.video.currentTime = clips[currentClipIndex][0];
							dp.play();
						}
					});

					this.videoPlayers[idSelector] = dp;

					// 隐藏 DPlayer 的控件
					const dpContainer = container.querySelector('.dplayer-controller');
					if (dpContainer) {
						dpContainer.style.display = 'none';
					}
				}
			},
			destroyPlayer(idSelector) {
				if (this.videoPlayers[idSelector]) {
					this.videoPlayers[idSelector].destroy();
					delete this.videoPlayers[idSelector];
				}
			}
		},
	}
</script>

<style lang="scss" scoped>
	.layout-container {
		width: 100%;
		margin: 20rpx 0;
	}

	/* 网格布局 */
	.grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		/* 默认2列 */
		gap: 0 10px;
		/* width: 100%; */
	}

	.title {
		text-align: center;
		margin: 15rpx 0;
		font-size: 28rpx;
		white-space: nowrap;
		/* 防止文本换行 */
		overflow: hidden;
		/* 隐藏溢出的文本 */
		text-overflow: ellipsis;
		/* 显示省略号 */
	}

	.nav {
		display: flex;
		justify-content: space-between;
		margin: 20rpx 0;

		.btn {
			padding: 8rpx 26rpx 8rpx 40rpx;
			font-size: 22rpx;
			display: flex;
			color: #999999;
			align-items: center;
			border: 2rpx solid #a6a6a6;
		}
	}

	/* 默认的媒体项样式 */
	.media-item {
		width: 100%;
		height: 260rpx;
		flex-direction: column;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/* 图片和视频 */
	.media {
		width: 100%;
		height: 240rpx;
		border-radius: 15rpx;
		object-fit: cover;
	}

	/* 前三项独占一行 */
	.full-width {
		height: 360rpx;

		grid-column: span 2;
		/* 跨 2 列 */
	}
</style>